package cn.tjad.tjad2.module.common.viewholder;

import android.support.v7.widget.RecyclerView;
import android.view.View;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import cn.tjad.tjad2.R;
import cn.tjad.tjad2.listener.OnItemClickListener;
import cn.tjad.tjad2.listener.OnItemLongClickListener;

public abstract class SimpleBaseViewHolder<T> extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {

    private OnItemClickListener onItemClickListener;
    private OnItemLongClickListener onItemLongClickListener;
    protected Map<Integer, View.OnClickListener> itemClickListenerMap;

    private int position;

    public SimpleBaseViewHolder(View itemView) {
        super(itemView);
    }

    public abstract void setData(T data, int position);

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
        if (this.onItemClickListener != null) {
            itemView.setOnClickListener(this);
        } else {
            itemView.setOnClickListener(null);
        }
    }

    public void setOnItemLongClickListener(OnItemLongClickListener onItemLongClickListener) {
        this.onItemLongClickListener = onItemLongClickListener;
        if (this.onItemLongClickListener != null) {
            itemView.setOnLongClickListener(this);
        } else {
            itemView.setOnLongClickListener(null);
        }
    }

    public void setItemClickListenerMap(Map<Integer, View.OnClickListener> itemClickListenerMap, T data) {
        this.itemClickListenerMap = itemClickListenerMap;
        if (this.itemClickListenerMap != null) {
            Set<Integer> keys = itemClickListenerMap.keySet();
            Iterator<Integer> keyIterator = keys.iterator();
            while (keyIterator.hasNext()) {
                Integer key = keyIterator.next();
                View.OnClickListener listener = itemClickListenerMap.get(key);
                View view = itemView.findViewById(key);
                if (view != null) {
                    view.setTag(R.id.list_item_data, data);
                    view.setOnClickListener(listener);
                }
            }
        }
    }


    public void fillData(T data,  int position) {
        this.position = position;
        setData(data, position);
    }

    @Override
    public void onClick(View view) {
        if (onItemClickListener != null) {
            onItemClickListener.onItemClick((View) itemView.getParent(), itemView, position);
        }
    }


    @Override
    public boolean onLongClick(View view) {
        if (onItemLongClickListener != null) {
            return onItemLongClickListener.onItemLongClick((View) itemView.getParent(), itemView, position);
        }
        return false;
    }
}
